'use client';

import { useState, useEffect, useRef } from 'react';
import { Play, Pause, Volume2, Sparkles, Heart, Star, Gamepad2 } from 'lucide-react';

interface Bomb {
  id: number;
  x: number;
  y: number;
  exploded: boolean;
}

interface Explosion {
  id: number;
  x: number;
  y: number;
}

export default function KleePage() {
  const [isPlaying, setIsPlaying] = useState(false);
  const [sparkles, setSparkles] = useState<Array<{ id: number; x: number; y: number; delay: number }>>([]);
  const audioRef = useRef<HTMLAudioElement>(null);

  // 游戏状态
  const [gameActive, setGameActive] = useState(false);
  const [score, setScore] = useState(0);
  const [bombs, setBombs] = useState<Bomb[]>([]);
  const [explosions, setExplosions] = useState<Explosion[]>([]);
  const [gameTime, setGameTime] = useState(30);
  const [showGameResult, setShowGameResult] = useState(false);

  useEffect(() => {
    // 创建闪闪发光的效果
    const newSparkles = Array.from({ length: 20 }, (_, i) => ({
      id: i,
      x: Math.random() * 100,
      y: Math.random() * 100,
      delay: Math.random() * 2,
    }));
    setSparkles(newSparkles);
  }, []);

  // 游戏计时器
  useEffect(() => {
    let timer: NodeJS.Timeout;
    if (gameActive && gameTime > 0) {
      timer = setTimeout(() => {
        setGameTime(gameTime - 1);
      }, 1000);
    } else if (gameActive && gameTime === 0) {
      endGame();
    }
    return () => clearTimeout(timer);
  }, [gameActive, gameTime]);

  // 生成炸弹
  useEffect(() => {
    let bombTimer: NodeJS.Timeout;
    if (gameActive) {
      bombTimer = setInterval(() => {
        const newBomb: Bomb = {
          id: Date.now() + Math.random(),
          x: Math.random() * 80 + 10, // 10% - 90% 位置
          y: Math.random() * 60 + 20, // 20% - 80% 位置
          exploded: false,
        };
        setBombs(prev => [...prev, newBomb]);

        // 3秒后自动移除未点击的炸弹
        setTimeout(() => {
          setBombs(prev => prev.filter(bomb => bomb.id !== newBomb.id));
        }, 3000);
      }, 800);
    }
    return () => clearInterval(bombTimer);
  }, [gameActive]);

  // 清理爆炸效果
  useEffect(() => {
    explosions.forEach(explosion => {
      setTimeout(() => {
        setExplosions(prev => prev.filter(exp => exp.id !== explosion.id));
      }, 1000);
    });
  }, [explosions]);

  const toggleMusic = () => {
    if (audioRef.current) {
      if (isPlaying) {
        audioRef.current.pause();
      } else {
        audioRef.current.play().catch(console.error);
      }
      setIsPlaying(!isPlaying);
    }
  };

  const startGame = () => {
    setGameActive(true);
    setScore(0);
    setBombs([]);
    setExplosions([]);
    setGameTime(30);
    setShowGameResult(false);
  };

  const endGame = () => {
    setGameActive(false);
    setBombs([]);
    setShowGameResult(true);
  };

  const explodeBomb = (bomb: Bomb) => {
    if (bomb.exploded) return;

    // 添加爆炸效果
    const explosion: Explosion = {
      id: Date.now(),
      x: bomb.x,
      y: bomb.y,
    };
    setExplosions(prev => [...prev, explosion]);

    // 增加分数
    setScore(prev => prev + 10);

    // 移除炸弹
    setBombs(prev => prev.filter(b => b.id !== bomb.id));
  };

  const kleeMessages = [
    "可莉最喜欢炸弹了！",
    "让我们一起去冒险吧！",
    "今天又是充满活力的一天！",
    "哒哒哒～炸弹就是最棒的！",
    "可莉会保护大家的！"
  ];

  const [currentMessage, setCurrentMessage] = useState(0);

  useEffect(() => {
    const interval = setInterval(() => {
      setCurrentMessage((prev) => (prev + 1) % kleeMessages.length);
    }, 3000);
    return () => clearInterval(interval);
  }, [kleeMessages.length]);

  return (
    <div className="min-h-screen bg-gradient-to-br from-pink-200 via-red-200 to-orange-200 overflow-hidden relative">
      {/* 背景音乐 */}
      <audio
        ref={audioRef}
        loop
        preload="auto"
        src="./kellBGM.mp3"
      />

      {/* 闪闪发光的背景效果 */}
      {sparkles.map((sparkle) => (
        <div
          key={sparkle.id}
          className="absolute animate-pulse"
          style={{
            left: `${sparkle.x}%`,
            top: `${sparkle.y}%`,
            animationDelay: `${sparkle.delay}s`,
          }}
        >
          <Sparkles className="text-yellow-400 w-4 h-4 animate-spin" />
        </div>
      ))}

      {/* 浮动的心形和星星 */}
      <div className="absolute top-10 left-10 animate-bounce">
        <Heart className="text-pink-500 w-8 h-8 fill-current" />
      </div>
      <div className="absolute top-20 right-20 animate-bounce" style={{ animationDelay: '0.5s' }}>
        <Star className="text-yellow-500 w-6 h-6 fill-current" />
      </div>
      <div className="absolute bottom-20 left-20 animate-bounce" style={{ animationDelay: '1s' }}>
        <Sparkles className="text-orange-500 w-7 h-7" />
      </div>

      {/* 游戏区域的炸弹 */}
      {gameActive && bombs.map((bomb) => (
        <div
          key={bomb.id}
          className="absolute cursor-pointer animate-bounce hover:scale-110 transition-transform"
          style={{
            left: `${bomb.x}%`,
            top: `${bomb.y}%`,
            animationDuration: '0.5s',
            zIndex:9999
          }}
          onClick={() => explodeBomb(bomb)}
        >
          <div className="text-4xl animate-pulse">💣</div>
        </div>
      ))}

      {/* 爆炸效果 */}
      {explosions.map((explosion) => (
        <div
          key={explosion.id}
          className="absolute animate-ping pointer-events-none"
          style={{
            left: `${explosion.x}%`,
            top: `${explosion.y}%`,
            zIndex:9999
          }}
        >
          <div className="text-6xl">💥</div>
        </div>
      ))}

      {/* 主要内容 */}
      <div className="container mx-auto px-4 py-8 relative z-10">
        {/* 音乐控制按钮 */}
        <div className="fixed top-6 right-6 z-20">
          <button
            onClick={toggleMusic}
            className="bg-red-500 hover:bg-red-600 text-white rounded-full p-4 shadow-lg transition-all duration-300 hover:scale-110 flex items-center gap-2"
          >
            {isPlaying ? <Pause className="w-6 h-6" /> : <Play className="w-6 h-6" />}
            <Volume2 className="w-4 h-4" />
          </button>
        </div>

        {/* 游戏控制面板 */}
        {gameActive && (
          <div className="fixed top-6 left-6 z-20 bg-white/90 backdrop-blur-sm rounded-2xl p-4 shadow-lg">
            <div className="flex flex-col gap-2 text-center">
              <div className="text-red-600 font-bold text-lg">
                分数: {score}
              </div>
              <div className="text-orange-600 font-semibold">
                时间: {gameTime}s
              </div>
              <button
                onClick={endGame}
                className="bg-red-500 text-white px-3 py-1 rounded-full text-sm hover:bg-red-600 transition-colors"
              >
                结束游戏
              </button>
            </div>
          </div>
        )}

        {/* 游戏结果弹窗 */}
        {showGameResult && (
          <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-30">
            <div className="bg-white rounded-2xl p-8 text-center shadow-2xl max-w-md mx-4">
              <div className="text-6xl mb-4">🎉</div>
              <h3 className="text-2xl font-bold text-red-600 mb-4">游戏结束！</h3>
              <p className="text-xl text-gray-700 mb-2">最终得分:</p>
              <p className="text-4xl font-bold text-orange-600 mb-6">{score} 分</p>
              <div className="space-y-3">
                <button
                  onClick={startGame}
                  className="w-full bg-gradient-to-r from-red-500 to-pink-500 text-white py-3 rounded-full font-semibold hover:from-red-600 hover:to-pink-600 transition-all"
                >
                  再玩一次
                </button>
                <button
                  onClick={() => setShowGameResult(false)}
                  className="w-full bg-gray-300 text-gray-700 py-3 rounded-full font-semibold hover:bg-gray-400 transition-all"
                >
                  关闭
                </button>
              </div>
            </div>
          </div>
        )}

        {/* 标题区域 */}
        <div className="text-center mb-12">
          <h1 className="text-6xl md:text-8xl font-bold text-red-600 mb-4 animate-pulse">
            ✨ 可莉 ✨
          </h1>
          <h2 className="text-2xl md:text-3xl text-red-500 font-semibold mb-2">
            真红骑士，出发！
          </h2>
          <h3 className="text-xl md:text-2xl text-orange-600">
            Let's Go, Crimson Knight!
          </h3>
          <div className="flex justify-center items-center gap-2 mt-4">
            <span className="text-4xl">💣</span>
            <span className="text-4xl">🎀</span>
            <span className="text-4xl">✨</span>
          </div>
        </div>

        {/* 可莉形象和介绍卡片 */}
        <div className="grid md:grid-cols-2 gap-8 items-center mb-12">
          {/* 可莉图片区域 */}
          <div className="bg-white/80 backdrop-blur-sm border-2 border-red-200 rounded-2xl shadow-2xl transform hover:scale-105 transition-all duration-300 p-8 text-center">
            <div className="relative">
              <img
                src="kell.jpg"
                alt="可莉"
                className="w-full max-w-sm mx-auto rounded-2xl shadow-lg animate-bounce"
                style={{ animationDuration: '3s' }}
              />
              <div className="absolute -top-4 -right-4 bg-yellow-400 rounded-full p-2 animate-spin">
                <Sparkles className="w-6 h-6 text-white" />
              </div>
            </div>
          </div>

          {/* 介绍文字区域 */}
          <div className="bg-white/80 backdrop-blur-sm border-2 border-red-200 rounded-2xl shadow-2xl p-8">
            <h3 className="text-3xl font-bold text-red-600 mb-6 text-center">
              关于可莉 💖
            </h3>
            <div className="space-y-4 text-lg text-gray-700">
              <p className="flex items-center gap-2">
                <span className="text-2xl">🌟</span>
                <span><strong>年龄：</strong> 永远的小孩子</span>
              </p>
              <p className="flex items-center gap-2">
                <span className="text-2xl">💣</span>
                <span><strong>爱好：</strong> 制作炸弹和冒险</span>
              </p>
              <p className="flex items-center gap-2">
                <span className="text-2xl">🎀</span>
                <span><strong>性格：</strong> 天真烂漫，活泼可爱</span>
              </p>
              <p className="flex items-center gap-2">
                <span className="text-2xl">🔥</span>
                <span><strong>元素：</strong> 火元素使者</span>
              </p>
              <p className="flex items-center gap-2">
                <span className="text-2xl">⚔️</span>
                <span><strong>称号：</strong> 真红骑士</span>
              </p>
            </div>
          </div>
        </div>

        {/* 可莉的话语展示 */}
        <div className="bg-gradient-to-r from-pink-100 to-red-100 border-2 border-red-300 rounded-2xl shadow-xl mb-12 p-8 text-center">
          <h3 className="text-2xl font-bold text-red-600 mb-4">可莉说：</h3>
          <p className="text-xl text-red-700 font-medium animate-pulse">
            "{kleeMessages[currentMessage]}"
          </p>
          <div className="flex justify-center mt-4 gap-2">
            {Array.from({ length: 5 }).map((_, i) => (
              <div
                key={i}
                className={`w-3 h-3 rounded-full transition-all duration-300 ${
                  i === currentMessage ? 'bg-red-500' : 'bg-red-200'
                }`}
              />
            ))}
          </div>
        </div>

        {/* 可莉的炸弹小游戏 */}
        <div className="bg-gradient-to-r from-yellow-100 to-orange-100 border-2 border-orange-300 rounded-2xl shadow-xl mb-12 p-8 text-center">
          <h3 className="text-3xl font-bold text-orange-600 mb-4 flex items-center justify-center gap-2">
            <Gamepad2 className="w-8 h-8" />
            可莉的炸弹小游戏
            <span className="text-4xl">💣</span>
          </h3>
          <p className="text-lg text-orange-700 mb-6">
            帮助可莉引爆炸弹！点击屏幕上出现的炸弹获得分数，30秒内看看你能得多少分！
          </p>
          {!gameActive && !showGameResult && (
            <button
              onClick={startGame}
              className="bg-gradient-to-r from-orange-500 to-red-500 hover:from-orange-600 hover:to-red-600 text-white px-8 py-4 text-xl font-bold rounded-full shadow-lg transform hover:scale-110 transition-all duration-300"
            >
              🎮 开始游戏！
            </button>
          )}
          {gameActive && (
            <div className="text-lg text-orange-700">
              <p className="animate-pulse">🎯 快速点击炸弹来获得分数！</p>
              <p className="text-sm mt-2">提示：炸弹会在3秒后自动消失哦～</p>
            </div>
          )}
        </div>

        {/* 互动按钮区域 */}
        <div className="text-center">
          <div className="flex flex-wrap justify-center gap-4">
            <button
              className="bg-gradient-to-r from-red-500 to-pink-500 hover:from-red-600 hover:to-pink-600 text-white px-8 py-4 text-lg font-semibold rounded-full shadow-lg transform hover:scale-110 transition-all duration-300"
              onClick={() => alert('哒哒哒～炸弹来啦！💣')}
            >
              💣 和可莉一起炸鱼
            </button>
            <button
              className="bg-gradient-to-r from-orange-500 to-yellow-500 hover:from-orange-600 hover:to-yellow-600 text-white px-8 py-4 text-lg font-semibold rounded-full shadow-lg transform hover:scale-110 transition-all duration-300"
              onClick={() => alert('可莉会保护大家的！✨')}
            >
              ✨ 一起去冒险
            </button>
            <button
              className="bg-gradient-to-r from-pink-500 to-purple-500 hover:from-pink-600 hover:to-purple-600 text-white px-8 py-4 text-lg font-semibold rounded-full shadow-lg transform hover:scale-110 transition-all duration-300"
              onClick={() => alert('可莉最喜欢大家了！💖')}
            >
              💖 给可莉一个抱抱
            </button>
          </div>
        </div>

        {/* 额外的互动元素 */}
        <div className="mt-12 text-center">
          <div className="bg-yellow-100 border-2 border-yellow-300 rounded-2xl p-6 mx-auto max-w-2xl">
            <h4 className="text-2xl font-bold text-orange-600 mb-4">🎵 可莉的冒险日记 🎵</h4>
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 text-sm">
              <div className="bg-white rounded-lg p-3 shadow">
                <div className="text-2xl mb-1">🏰</div>
                <div className="font-semibold">蒙德城</div>
                <div className="text-gray-600">可莉的家</div>
              </div>
              <div className="bg-white rounded-lg p-3 shadow">
                <div className="text-2xl mb-1">🎣</div>
                <div className="font-semibold">炸鱼</div>
                <div className="text-gray-600">最爱的活动</div>
              </div>
              <div className="bg-white rounded-lg p-3 shadow">
                <div className="text-2xl mb-1">📚</div>
                <div className="font-semibold">炸弹手册</div>
                <div className="text-gray-600">珍藏书籍</div>
              </div>
              <div className="bg-white rounded-lg p-3 shadow">
                <div className="text-2xl mb-1">🧸</div>
                <div className="font-semibold">嘟嘟可</div>
                <div className="text-gray-600">最好朋友</div>
              </div>
            </div>
          </div>
        </div>
      </div>

      {/* 底部装饰 */}
      <div className="absolute bottom-0 left-0 right-0 h-20 bg-gradient-to-t from-red-300/50 to-transparent" />

      {/* 飘动的花瓣效果 */}
      <div className="absolute top-1/4 left-1/4 animate-ping">
        <div className="text-pink-400 text-2xl">🌸</div>
      </div>
      <div className="absolute top-1/3 right-1/3 animate-ping" style={{ animationDelay: '1s' }}>
        <div className="text-red-400 text-2xl">🌺</div>
      </div>
      <div className="absolute top-2/3 left-1/6 animate-ping" style={{ animationDelay: '2s' }}>
        <div className="text-orange-400 text-2xl">🌼</div>
      </div>
    </div>
  );
}
